<template>
	<view>
		<u-navbar :is-back="false" title="　" :border-bottom="false">
			<view class="u-flex u-row-right" style="width: 100%;">
				<view class="camera u-flex u-row-center">
					<u-icon name="setting-fill" color="#000000" size="48" @click="handleToEdit"></u-icon>
				</view>
			</view>
		</u-navbar>
		<view class="u-flex user-box u-p-l-30 u-p-r-20 u-p-b-30">
			<view class="u-m-r-30">
				<u-avatar :src="pic" :text="user_info.name" bg-color="#92c8ff" :show-level="user_info.name ? true : false" size="140"></u-avatar>
			</view>
			<view class="u-flex-1">
				<view v-if="!access_token" class="u-font-18 u-p-b-20" @click="handleToLogin">点击登录/注册</view>
				<view v-else class="u-font-18 u-p-b-20">
					{{user_info.name}}
				</view>
				<view class="u-font-14 u-tips-color">阅读{{readTime}}分 读过{{idList.length}}本</view>
			</view>
			<!-- 		<view class="u-m-l-10 u-p-10">
				<u-icon name="setting" color="#969799" size="28" @click="handleToEdit"></u-icon>
			</view> -->
			<view class="u-m-l-10 u-p-10">
				<u-icon name="arrow-right" color="#969799" size="28"></u-icon>
			</view>
		</view>

		<view class="u-m-t-20">
			<u-cell-group>
				<u-cell-item icon="grid" title="我的书架" @click="handleToShelf"></u-cell-item>
				<u-cell-item icon="clock" title="阅读历史" @click="handleToHistory"></u-cell-item>
				<u-cell-item icon="hourglass" title="阅读时长" @click="handleToReadTime"></u-cell-item>
				<u-cell-item icon="setting" title="阅读设置" @click="handleToReadSetting"></u-cell-item>
			</u-cell-group>
		</view>

		<view class="u-m-t-20">
			<u-cell-group>
				<u-cell-item icon="trash" title="清除缓存" @click="handleToClearStorage"></u-cell-item>
				<u-cell-item icon="share" title="分享给好友" @click="shareFc()"></u-cell-item>
				<u-cell-item icon="error-circle" title="关于我们" @click="aboutUS"></u-cell-item>
				<u-cell-item icon="bookmark" title="版本更新" :arrow="false" @click="handleToUpdate">
					<text slot="right-icon" :style="isUpdate?'color:rgb(146, 200, 255)':''">{{ isUpdate ? '监测到新版本' : '已是最新版本' }}
					</text>
				</u-cell-item>
			</u-cell-group>
		</view>
		<u-modal v-model="clearShow" :content="content" @confirm="confirmClearStorage" show-cancel-button></u-modal>
		<u-modal v-model="updateShow" :title="updateInfo.update_title" :content="updateInfo.update_content"
		 :show-cancel-button="true" @confirm="comfirmToUpdate"></u-modal>
		<!-- 图片展示由自己实现 -->
		<view class="flex_row_c_c modalView" :class="qrShow?'show':''" @tap="hideQr()">
			<view class="flex_column">
				<view class="backgroundColor-white padding1vh border_radius_10px">
					<image :src="poster.finalPath || ''" mode="widthFix" class="posterImage"></image>
				</view>
				<view class="flex_row marginTop2vh">
					<u-button :custom-style="{background:'#92c8ff',color:'#fff','border-color':'#92c8ff'}" :hair-line="false" size="mini" @click.prevent.stop="saveImage">保存图片</u-button>
					<u-button :custom-style="{background:'#92c8ff',color:'#fff','border-color':'#92c8ff'}" :hair-line="false" size="mini" @click.prevent.stop="share">分享图片</u-button>
				</view>
			</view>
		</view>
		<!-- 画布 -->
		<view class="hideCanvasView">
			<canvas class="hideCanvas" canvas-id="default_PosterCanvasId" :style="{width: (poster.width||10) + 'px', height: (poster.height||10) + 'px'}"></canvas>
		</view>
		<u-toast ref="uToast" />
		<u-tabbar v-model="currentTabbar" :list="vuex_tabbar"></u-tabbar>
	</view>
</template>

<script>
	import {
		verionUpdate
	} from '../../api/common'
	import _app from '../../utils/QS-SharePoster/app.js';
	import {
		getSharePoster
	} from '../../utils/QS-SharePoster/QS-SharePoster.js';
	export default {
		data() {
			return {
				pic: 'http://foglake.sanye666.top/images/sanye.png',
				show: true,
				currentTabbar: 0,
				content: '确认要清空本地缓存?',
				clearShow: false,
				readTime: 0,
				isUpdate: false,
				version: '1.0.0',
				updateShow: false,
				updateInfo: {
					update_title: '',
					update_content: '',
					update_url: ''
				},
				idList: [],
				poster: {},
				qrShow: false,
				canvasId: 'default_PosterCanvasId'
			}
		},
		onLoad() {
			this.getReadTime();
			// #ifdef APP-PLUS
			this.getUpdateInfo();
			// #endif
		},
		onShow() {
			this.getReadTime();
			// #ifdef APP-PLUS
			this.getUpdateInfo();
			// #endif
		},
		onPullDownRefresh() {
			this.getReadTime();
			setTimeout(() => {
				this.$refs.uToast.show({
					title: '刷新成功',
					type: 'success',
					position: 'top'
				});
				uni.stopPullDownRefresh()
			}, 1000);
		},
		methods: {
			handleToShelf() {
				uni.switchTab({
					url: '/pages/shelf/shelf'
				})
			},
			handleToLogin() {
				uni.navigateTo({
					url: '/pages/user/login',
					animationType: 'slide-in-bottom',
					animationDuration: 200
				})
			},
			handleToHistory() {
				uni.navigateTo({
					url: '/pages/history/history'
				})
			},
			handleToReadTime() {
				if (this.readTime != 0) {
					uni.navigateTo({
						url: '/pages/time/time'
					})
				} else {
					this.$refs.uToast.show({
						title: '您的阅读时间太短了,还不能查看',
						type: 'warning',
						position: 'top'
					})
				}
			},
			handleToReadSetting() {
				uni.navigateTo({
					url: '/pages/user/setting'
				})
			},
			handleToShare() {},
			aboutUS() {
				uni.navigateTo({
					url: `/pages/user/about?version=${this.version}`
				})
			},
			// 获取阅读时间
			getReadTime() {
				let read_time = uni.getStorageSync('read_time');
				if (read_time) {
					let readTime = 0;
					let readTimeList = JSON.parse(read_time);
					let idList = [];
					readTimeList.forEach(item => {
						if (item.bookId && item.readTimeEnd && item.readTimeStart) {
							readTime += this.getTime(item.readTimeStart, item.readTimeEnd)
						}
						idList.push(item.bookId)
					})
					let min = Math.floor((readTime / 1000 / 60) << 0);
					this.readTime = min;
					this.idList = [...new Set(idList)];
				} else {
					this.readTime = 0;
				}
			},
			getTime(start, end) {
				return new Date(end).getTime() - new Date(start).getTime()
			},
			handleToEdit() {
				if (this.access_token) {
					uni.navigateTo({
						url: '/pages/user/edit'
					})
				} else {
					this.$refs.uToast.show({
						title: '请先登录',
						type: 'warning'
					})
				}
			},
			handleToClearStorage() {
				this.clearShow = true;
			},
			confirmClearStorage() {
				uni.clearStorage();
				this.$refs.uToast.show({
					title: '清除成功！',
					type: 'success'
				})
			},
			getUpdateInfo() {
				plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
					this.version = wgtinfo.version
					let header = {
						version: this.version,
						osType: 1
					}
					verionUpdate(header).then(res => {
						if (res.data.updateInfo.is_update == 1) {
							this.isUpdate = true;
							this.updateInfo = res.data.updateInfo;
						} else {
							this.isUpdate = false;
						}
					})
				});
			},
			handleToUpdate() {
				if (this.isUpdate) {
					this.updateShow = true;
				}
			},
			comfirmToUpdate() {
				// #ifdef APP-PLUS  
				this.$refs.uToast.show({
					title: '新版本开始下载',
					type: 'success',
					position: 'top'
				})
				const _self = this;
				var dtask = plus.downloader.createDownload(this.updateInfo.update_url, {}, function(d, status) {
					if (status == 200) {
						plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename), {}, {}, function(error) {
							_self.$refs.uToast.show({
								title: '安装失败',
								type: 'error',
								position: 'top'
							})
						})
					} else {
						_self.$refs.uToast.show({
							title: '更新失败',
							type: 'error',
							position: 'top'
						})
					}
				});
				dtask.start();
				// #endif
			},

			async shareFc() {
				try {
					const that = this;
					_app.log('准备生成:' + new Date())
					const d = await getSharePoster({
						_this: this, //若在组件中使用 必传
						type: 'testShareType',
						formData: {
							//访问接口获取背景图携带自定义数据
						},
						posterCanvasId: this.canvasId, //canvasId
						delayTimeScale: 20, //延时系数
						/* background: {
							width: 1080,
							height: 1920,
							backgroundColor: '#666'
						}, */
						drawArray: ({
							bgObj,
							type,
							bgScale
						}) => {
							const dx = bgObj.width * 0.05;
							const fontSize = bgObj.width * 0.045;
							const lineHeight = bgObj.height * 0.04;
							//可直接return数组，也可以return一个promise对象, 但最终resolve一个数组, 这样就可以方便实现后台可控绘制海报
							return new Promise((rs, rj) => {
								rs([{
										type: 'custom',
										setDraw(Context) {
											Context.setFillStyle('black');
											Context.setGlobalAlpha(0.3);
											Context.fillRect(0, bgObj.height - bgObj.height * 0.2, bgObj.width, bgObj.height * 0.2);
											Context.setGlobalAlpha(1);
										}
									},
									{
										type: 'image',
										url: '/static/image/logo.png',
										alpha: .7,
										dx,
										dy: bgObj.height - bgObj.width * 0.25,
										infoCallBack(imageInfo) {
											let scale = bgObj.width * 0.2 / imageInfo.height;
											return {
												circleSet: {
													x: imageInfo.width * scale / 2,
													y: bgObj.width * 0.2 / 2,
													r: bgObj.width * 0.2 / 2
												}, // 圆形图片 , 若circleSet与roundRectSet一同设置 优先circleSet设置
												dWidth: imageInfo.width * scale, // 因为设置了圆形图片 所以要乘以2
												dHeight: bgObj.width * 0.2,
												/* roundRectSet: { // 圆角矩形
													r: imageInfo.width * .1
												} */
											}
										}
									},
									{
										type: 'text',
										text: '三叶阅读',
										size: fontSize,
										color: 'white',
										// alpha: .5,
										textAlign: 'left',
										textBaseline: 'middle',
										infoCallBack(textLength) {
											_app.log('index页面的text的infocallback ，textlength:' + textLength);
											return {
												dx: (bgObj.width - textLength - fontSize) * 0.35,
												dy: bgObj.height - lineHeight * 3
											}
										},
										serialNum: 0,
										id: 'tag1' //自定义标识
									},
									{
										type: 'text',
										text: '读书用三叶 免费任翻阅',
										fontWeight: 'bold',
										size: fontSize,
										color: 'white',
										alpha: .75,
										textAlign: 'left',
										textBaseline: 'middle',
										serialNum: 1,
										allInfoCallback({ //v3.0.1 更新 可以获取drawArray中全部数据
											drawArray
										} = {}) {
											const obj = drawArray.find(item => item.id === 'tag1');
											/* return {
												dx: obj.dx,
												dy: obj.dy + lineHeight
											} */
											//也可以return promise对象
											return new Promise((rs, rj) => {
												setTimeout(() => {
													rs({
														dx: obj.dx,
														dy: obj.dy + lineHeight * 1.5
													});
												}, 1);
											});
										}
									},
									{
										type: 'qrcode',
										text: '下载地址',
										size: bgObj.width * 0.2,
										dx: bgObj.width * 0.75,
										dy: bgObj.height - bgObj.width * 0.25
									}
								]);
							})
						},
						setCanvasWH: ({
							bgObj,
							type,
							bgScale
						}) => { // 为动态设置画布宽高的方法，
							this.poster = bgObj;
						}
					});
					_app.log('海报生成成功, 时间:' + new Date() + '， 临时路径: ' + d.poster.tempFilePath)
					this.poster.finalPath = d.poster.tempFilePath;
					this.qrShow = true;
				} catch (e) {
					_app.hideLoading();
					_app.showToast(JSON.stringify(e));
					console.log(JSON.stringify(e));
				}
			},
			saveImage() {
				// #ifdef APP-PLUS
				const _self = this;
				uni.saveImageToPhotosAlbum({
					filePath: this.poster.finalPath,
					success(res) {
						_app.showToast('保存成功');
					},
					fail(error) {
						_self.$refs.uToast.show({
							title: error,
							type: 'error',
							position: 'top'
						})
					}
				})
				// #endif
			},
			share() {
				// #ifdef APP-PLUS
				_app.getShare(false, false, 2, '', '', '', this.poster.finalPath, false, false);
				// #endif
			},
			hideQr() {
				this.qrShow = false;
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F5F8FC;
	}

	.camera {
		width: 54px;
		height: 44px;

		&:active {
			background-color: #ededed;
		}
	}

	.user-box {
		background-color: #fff;
	}

	.hideCanvasView {
		position: relative;
	}

	.hideCanvas {
		position: fixed;
		top: -99999upx;
		left: -99999upx;
		z-index: -99999;
	}

	.flex_row_c_c {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

	.modalView {
		width: 100%;
		height: 100%;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		opacity: 0;
		outline: 0;
		transform: scale(1.2);
		perspective: 2500upx;
		background: rgba(0, 0, 0, 0.6);
		transition: all .3s ease-in-out;
		pointer-events: none;
		backface-visibility: hidden;
		z-index: 999;
	}

	.modalView.show {
		opacity: 1;
		transform: scale(1);
		pointer-events: auto;
	}

	.flex_column {
		display: flex;
		flex-direction: column;
	}

	.backgroundColor-white {
		background-color: white;
	}

	.border_radius_10px {
		border-radius: 10px;
	}

	.padding1vh {
		padding: 1vh;
	}

	.posterImage {
		width: 60vw;
	}

	.flex_row {
		display: flex;
		flex-direction: row;
	}

	.marginTop2vh {
		margin-top: 2vh;
	}
</style>
